
import logging
import time

logger = logging.getLogger(__name__)

MODULES_STATUS = {}

def enhanced_start_monitoring():
    """增强版启动监控"""
    print("\n🟢 启动实时监控...")
    try:
        # 尝试多种方式获取监控系统
        monitor_class = None

        # 方式1：从MODULES_STATUS获取
        if MODULES_STATUS.get('monitoring_system'):
            monitor_class = MODULES_STATUS['monitoring_system']
            print("✅ 从模块状态获取监控系统")

        # 方式2：直接导入
        if not monitor_class:
            try:
                from real_time_monitoring_system import RealTimeMonitoringSystem
                monitor_class = RealTimeMonitoringSystem
                print("✅ 直接导入监控系统")
            except ImportError:
                pass

        # 方式3：尝试导入实时打板监控系统
        if not monitor_class:
            try:
                from 实时打板监控系统 import RealTimeLimitUpMonitor
                monitor_class = RealTimeLimitUpMonitor
                print("✅ 使用实时打板监控系统")
            except ImportError:
                pass

        if not monitor_class:
            print("❌ 实时监控模块不可用")
            print("💡 请确保以下模块之一可用:")
            print("   - real_time_monitoring_system.py")
            print("   - 实时打板监控系统.py")
            return False

        # 创建监控实例
        config = {
            'update_interval': 30,
            'alert_threshold': 9.5
        }

        monitor = monitor_class(config) if monitor_class.__name__ == 'RealTimeLimitUpMonitor' else monitor_class()

        # 启动监控
        if hasattr(monitor, 'start_monitoring'):
            monitor.start_monitoring()
        elif hasattr(monitor, 'start'):
            monitor.start()
        else:
            print("❌ 监控系统缺少启动方法")
            return False

        print("✅ 实时监控已启动。")
        print("ℹ️ 监控系统正在后台运行...")
        return True

    except Exception as e:
        logger.error(f"启动实时监控失败: {e}")
        print(f"❌ 启动实时监控失败: {e}")
        return False

def enhanced_stop_monitoring():
    """增强版停止监控"""
    print("\n🔴 停止实时监控...")
    try:
        # 尝试多种方式获取监控系统
        monitor_class = None

        # 方式1：从MODULES_STATUS获取
        if MODULES_STATUS.get('monitoring_system'):
            monitor_class = MODULES_STATUS['monitoring_system']

        # 方式2：直接导入
        if not monitor_class:
            try:
                from real_time_monitoring_system import RealTimeMonitoringSystem
                monitor_class = RealTimeMonitoringSystem
            except ImportError:
                pass

        # 方式3：尝试导入实时打板监控系统
        if not monitor_class:
            try:
                from 实时打板监控系统 import RealTimeLimitUpMonitor
                monitor_class = RealTimeLimitUpMonitor
            except ImportError:
                pass

        if not monitor_class:
            print("❌ 实时监控模块不可用")
            return False

        # 创建监控实例并停止
        config = {
            'update_interval': 30,
            'alert_threshold': 9.5
        }

        monitor = monitor_class(config) if monitor_class.__name__ == 'RealTimeLimitUpMonitor' else monitor_class()

        # 停止监控
        if hasattr(monitor, 'stop_monitoring'):
            monitor.stop_monitoring()
        elif hasattr(monitor, 'stop'):
            monitor.stop()
        else:
            print("❌ 监控系统缺少停止方法")
            return False

        print("✅ 实时监控已停止。")
        return True

    except Exception as e:
        logger.error(f"停止实时监控失败: {e}")
        print(f"❌ 停止实时监控失败: {e}")
        return False

def enhanced_configure_monitoring():
    """专业参数配置系统"""
    print("\n⚙️ 配置监控参数")
    print("此功能在GUI版本中提供更友好的交互体验。")
    # ... (此处省略了详细的配置逻辑)

def enhanced_monitoring_statistics():
    """增强版统计报告"""
    print("\n📊 查看监控统计")
    try:
        # 尝试多种方式获取监控系统
        monitor_class = None

        # 方式1：从MODULES_STATUS获取
        if MODULES_STATUS.get('monitoring_system'):
            monitor_class = MODULES_STATUS['monitoring_system']

        # 方式2：直接导入
        if not monitor_class:
            try:
                from real_time_monitoring_system import RealTimeMonitoringSystem
                monitor_class = RealTimeMonitoringSystem
            except ImportError:
                pass

        if not monitor_class:
            print("❌ 实时监控模块不可用")
            print("💡 显示基本统计信息:")
            print("  - 监控状态: 未启动")
            print("  - 可用监控系统: 检查中...")

            # 检查可用的监控系统
            available_systems = []
            try:
                from real_time_monitoring_system import RealTimeMonitoringSystem
                available_systems.append("RealTimeMonitoringSystem")
            except ImportError:
                pass

            try:
                from 实时打板监控系统 import RealTimeLimitUpMonitor
                available_systems.append("RealTimeLimitUpMonitor")
            except ImportError:
                pass

            if available_systems:
                print(f"  - 可用系统: {', '.join(available_systems)}")
            else:
                print("  - 可用系统: 无")
            return

        # 创建监控实例并获取统计
        config = {
            'update_interval': 30,
            'alert_threshold': 9.5
        }

        monitor = monitor_class(config) if monitor_class.__name__ == 'RealTimeLimitUpMonitor' else monitor_class()

        # 获取统计信息
        if hasattr(monitor, 'get_statistics'):
            stats = monitor.get_statistics()
            print(f"  - 监控时长: {stats.get('duration', 0):.2f} 秒")
            print(f"  - 处理信号: {stats.get('signals_processed', 0)} 个")
            print(f"  - 监控状态: {stats.get('status', '未知')}")
        else:
            print("  - 监控系统: 已加载")
            print("  - 统计功能: 不支持详细统计")
            print("  - 状态: 可用")

    except Exception as e:
        logger.error(f"查看监控统计失败: {e}")
        print(f"❌ 查看监控统计失败: {e}")

def realtime_monitoring_menu(modules_status):
    """增强版实时监控系统"""
    global MODULES_STATUS
    MODULES_STATUS = modules_status

    while True:
        print("\n" + "="*60)
        print("📡 增强版实时监控系统")
        print("="*60)
        print("1. 🟢 启动实时监控")
        print("2. 🔴 停止实时监控")
        print("3. ⚙️ 配置监控参数")
        print("4. 📊 查看监控统计")
        print("5. 🔙 返回主菜单")

        choice = input("\n请选择操作 (1-5): ").strip()

        try:
            if choice == '1': enhanced_start_monitoring()
            elif choice == '2': enhanced_stop_monitoring()
            elif choice == '3': enhanced_configure_monitoring()
            elif choice == '4': enhanced_monitoring_statistics()
            elif choice == '5': break
            else: print("❌ 无效选择，请输入1-5")
        except Exception as e:
            logger.error(f"实时监控操作错误: {e}")
            print(f"❌ 操作失败: {e}")
        
        input("\n按回车键继续...")
